<!--
 * @Description: 客户画像分析页面 - 提供单个客户的详细画像分析和行为特征
 * @Author: lujq
 * @Date: 2024-12-21
 * @LastEditors: lujq
 * @LastEditTime: 2024-12-21 16:30:00
-->
<template>
  <div class="customer-list">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索客户姓名、公司名称"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchForm.level"
            placeholder="客户等级"
            clearable
            @change="handleSearch"
          >
            <el-option label="钻石客户" value="diamond" />
            <el-option label="黄金客户" value="gold" />
            <el-option label="白银客户" value="silver" />
            <el-option label="青铜客户" value="bronze" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchForm.status"
            placeholder="客户状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="活跃" value="active" />
            <el-option label="非活跃" value="inactive" />
            <el-option label="黑名单" value="blacklist" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchForm.customerType"
            placeholder="客户类型"
            clearable
            @change="handleSearch"
          >
            <el-option label="企业客户" value="enterprise" />
            <el-option label="个人客户" value="individual" />
          </el-select>
        </el-col>
        <el-col :span="6" style="white-space: nowrap">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 客户列表表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="customerList"
        style="width: 100%"
        @row-click="handleRowClick"
        row-class-name="table-row"
      >
        <el-table-column prop="name" label="客户姓名" min-width="120" fixed="left">
          <template #default="{ row }">
            <div class="customer-name-cell">
              <el-avatar :size="32" class="customer-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="company" label="公司名称" min-width="150" show-overflow-tooltip />

        <el-table-column prop="level" label="客户等级" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)" size="small">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="totalAmount" label="总消费金额" min-width="120" sortable>
          <template #default="{ row }">
            <span class="amount">¥{{ formatAmount(row.totalAmount) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="totalOrders"
          label="订单数量"
          min-width="100"
          sortable
          align="center"
        />

        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="lastOrderDate" label="最后下单" min-width="100">
          <template #default="{ row }">
            {{ formatDate(row.lastOrderDate) }}
          </template>
        </el-table-column>

        <el-table-column prop="salesManager" label="销售经理" min-width="100" />

        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="viewDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 客户详情抽屉 -->
    <CustomerDetailDrawer v-model="detailDialogVisible" :customer="currentCustomer" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Search, Refresh, View } from '@element-plus/icons-vue'
import { getCustomerList } from '@/api/customer'
import type { Customer, PageParams } from '@/types'
import CustomerDetailDrawer from './components/CustomerDetailDrawer.vue'

// 响应式数据
const loading = ref(false)
const customerList = ref<Customer[]>([])
const detailDialogVisible = ref(false)
const currentCustomer = ref<Customer | null>(null)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  level: '',
  status: '',
  customerType: '',
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0,
})

// 获取客户列表
const getCustomerListData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.size,
      ...searchForm,
    }

    const response = await getCustomerList(params)
    customerList.value = response.data.list
    pagination.total = response.data.total
  } catch (error) {
    console.error('获取客户列表失败:', error)
    ElMessage.error('获取客户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  getCustomerListData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    level: '',
    status: '',
    customerType: '',
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  getCustomerListData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getCustomerListData()
}

// 行点击事件
const handleRowClick = (row: Customer) => {
  viewDetail(row)
}

// 查看详情
const viewDetail = (customer: Customer) => {
  currentCustomer.value = customer
  detailDialogVisible.value = true
}

// 工具函数
const getLevelText = (level: string) => {
  const levelMap: Record<string, string> = {
    diamond: '钻石客户',
    gold: '黄金客户',
    silver: '白银客户',
    bronze: '青铜客户',
  }
  return levelMap[level] || '未知等级'
}

const getLevelType = (level: string) => {
  const typeMap: Record<string, string> = {
    diamond: 'danger',
    gold: 'warning',
    silver: 'info',
    bronze: 'success',
  }
  return typeMap[level] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '活跃',
    inactive: '非活跃',
    blacklist: '黑名单',
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    active: 'success',
    inactive: 'warning',
    blacklist: 'danger',
  }
  return typeMap[status] || 'info'
}

const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  })
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 组件挂载
onMounted(() => {
  console.log('组件已挂载，开始加载数据...')
  getCustomerListData()
})

// 手动触发数据加载（用于调试）
const debugLoadData = () => {
  console.log('手动触发数据加载')
  getCustomerListData()
}

// 暴露给全局用于调试
if (typeof window !== 'undefined') {
  ;(window as any).debugLoadData = debugLoadData
}
</script>

<style scoped>
.customer-list {
  padding: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.customer-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.customer-avatar {
  flex-shrink: 0;
}

.name {
  font-weight: 500;
}

.amount {
  font-weight: 600;
  color: #409eff;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.table-row {
  cursor: pointer;
}

.table-row:hover {
  background-color: #f5f7fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-name-cell {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .pagination-container {
    margin-top: 16px;
  }
}
</style>
